<script setup lang='ts'>
import { recommendDel, recommendEnable, recommendList, recommendSnapshotDel, recommendSnapshotList, recommendSnapshotSave } from '@fl/api/advertising-api/page-config-recommend'

import { SearchTable } from '@fl/components'
import { cloneDeep } from 'lodash-es'
import { reactive } from 'vue'
import { useDicts } from '../../../goods-management/hooks/use-dicts'
import addOrEditGoods from './recommend-addOrEdit.vue'

const props = defineProps<{
    activeTreeId?: number | string
}>()

const { activeTreeId } = toRefs(props)

const timeList = ref<any>([])
const currentTime = ref(0)
const isTimeListEmpty = ref<boolean>(false)

const { useDict } = useDicts()
const tableHeight = ref<number>(360)
const visible = ref<boolean>(false)
const editId = ref<string>()
const addOrEditRef = ref()
const records = ref<any>([])
const currentSnapshotId = ref<number | undefined>(undefined)

const total = computed(() => {
    return records.value.length
})
// 弹框相关
const initForm = {
    activeEnd: '', // 生效结束时间
    activeStart: '', // 生效开始时间
    groupSnapshotId: undefined, // 商品排期id
    id: undefined, // 商品id
    projectName: '', // 商品名称
    plate: '', // 业务类型
}

const goodsForm = ref(cloneDeep(initForm)) // 当前楼盘信息，包含分期id，后面会用详情、单独维护分期id

// 查询列表
const isLoading = ref(false)

// getSnapList(activeTreeId.value)

watchEffect(() => {
    if (activeTreeId.value) {
        getSnapList(activeTreeId.value)
    }
})

// 2.获取分期列表以及默认选中第一条
async function getSnapList(groupId) {
    console.log('Jinlaile', groupId)
    if (!groupId)
        return
    try {
        const res2 = await recommendSnapshotList({ pageResourceId: groupId })
        isLoading.value = false

        // 处理timeList
        if (res2.length) {
            isTimeListEmpty.value = false
            timeList.value = res2.map(item => ({
                ...item,
                activeTime: [item.activeStart, item.activeEnd],
            }))
            // 根据当前时间判断时间分期高亮index
            currentTime.value = timeList.value.reduce((pre, cur, index) => {
                const startTime = new Date(cur.activeStart).getTime()
                const endTime = new Date(cur.activeEnd).getTime()
                const now = new Date().getTime()
                if (now < endTime && now > startTime) {
                    return index
                }
                else {
                    return 0
                }
            }, 0)
            console.log('currentTime', currentTime.value)
            selectTime(currentTime.value, timeList.value[currentTime.value])
        }
        else {
            isTimeListEmpty.value = true
            timeList.value = [{
                activeTime: [],
                groupId: activeTreeId.value,
            }]
            records.value = []
        }
    }
    catch (error) {
        isLoading.value = false
    }
}

// 3.查询商品组快照素材资源信息
async function getGoodsList(groupSnapshotId) {
    currentSnapshotId.value = groupSnapshotId
    console.log('getGoodsList', groupSnapshotId)
    const res3 = await recommendList({
        snapshotId: groupSnapshotId,
    })
    console.log('getGoodsList', res3)
    records.value = res3.reduce((pre, cur, index) => {
        cur.tempSort = index + 1
        cur.plate = String(cur.plate)
        cur.activeStatus = cur.activeStatus ?? 0
        pre.push(cur)
        return pre
    }, [])
}

// 选择分期
function selectTime(index, item) {
    currentTime.value = index
    // goodsForm.value.groupSnapshotId = item.id
    currentSnapshotId.value = item.id
    if (item.activeStart && item.activeEnd) {
        goodsForm.value.activeStart = item.activeStart
        goodsForm.value.activeEnd = item.activeEnd
    }
    else {
        records.value = []
    }
    item.id && getGoodsList(item.id)
}

// 设置分期时间
async function changeTime(val, item, index) {
    await recommendSnapshotSave({
        activeEnd: val[1],
        activeStart: val[0],
        pageResourceId: activeTreeId.value,
        id: item.id,
    }).then((res) => {
        item.activeTime = [res.activeStart, res.activeEnd]
        item.id = res.id
    }).catch(() => {
        item.activeTime = []
    })
    getSnapList(activeTreeId.value) // 重新获取分期列表
    selectTime(index, item)
}

// 新增分期
function addAdTime(item, index) {
    const time = cloneDeep({
        activeTime: [],
        groupId: activeTreeId.value,
    })
    timeList.value.push(time)
    selectTime(index + 1, time)
}

// 删除分期
function delTime(item, index) {
    if (item.activeTime?.length) {
        ElMessageBox.confirm(
            '您确认要删除这个商品排期吗',
            '删除',
            {
                cancelButtonText: '取消',
                confirmButtonText: '删除',
                type: 'warning',
            },
        )
            .then(() => {
                recommendSnapshotDel({
                    id: item.id,
                }).then(() => {
                    timeList.value.splice(index, 1)
                    let currentKey = 0
                    if (currentTime.value === index) {
                        if (index !== timeList.value.length)
                            currentKey = index
                        selectTime(currentKey, timeList.value[currentKey])
                    }
                    ElMessage({
                        message: '删除成功',
                        type: 'success',
                    })
                })
            }).catch(() => {
                ElMessage({
                    message: '取消删除',
                    type: 'info',
                })
            })
    }
    else {
        timeList.value.splice(index, 1)
        let currentKey = 0
        if (currentTime.value === index) {
            if (index !== timeList.value.length)
                currentKey = index
            selectTime(currentKey, timeList.value[currentKey])
        }
    }
}

// 启用禁用
function switchActiveStatus(row) {
    console.log('switchActiveStatus', row)
    const params = {
        id: row.id,
        enable: row.activeStatus,
    }
    recommendEnable(params).then(() => {
        const tips = row.activeStatus === 1 ? '已启用' : '已禁用'
        ElMessage({
            message: tips,
            type: row.activeStatus === 1 ? 'success' : 'info',
        })
        getGoodsList(currentSnapshotId.value) // 此处后续单独维护分期id
    })
}

// 添加
function goToAdd() {
    visible.value = true
    addOrEditRef.value.reset() // 先消除未填写的警告
    resetAdForm()
}

function resetAdForm() {
    goodsForm.value.projectName = ''
    goodsForm.value.plate = ''
    goodsForm.value.id = undefined
}

// 列表：编辑
function goToEdit(row: any) {
    visible.value = true
    editId.value = row.id
}

// 列表：删除
function deleteConfirm(row: any) {
    const { id, projectName } = row
    ElMessageBox.confirm(
        `您确认要删除商品『${projectName}』吗`,
        '删除',
        {
            cancelButtonText: '取消',
            confirmButtonText: '删除',
            type: 'warning',
        },
    )
        .then(() => {
            recommendDel({
                id,
            }).then(() => {
                getGoodsList(currentSnapshotId.value)
                ElMessage({
                    message: '删除成功',
                    type: 'success',
                })
            })
        }).catch(() => {
            ElMessage({
                message: '取消删除',
                type: 'info',
            })
        })
}

defineExpose({
    getSnapList,
})

const gridOptions = reactive({
    columns: [
        { title: '序号', type: 'seq', width: 60 },
        { field: 'plate', slots: { default: 'plate' }, title: '业务类型' },
        { field: 'projectName', title: '楼盘/产品名称' },
        { field: 'activeStatus', slots: { default: 'activeStatus' }, title: '启用/禁用' },
        { fixed: 'right', slots: { default: 'operate' }, title: '操作', width: 120 },
    ],
})
</script>

<template>
    <div class="mb20 flex">
        <div class="top">
            <ElButton type="primary"
                      :disabled="isTimeListEmpty"
                      @click="goToAdd"
            >
                <div class="i-ic:baseline-add size-16" />
                添加
            </ElButton>
        </div>
    </div>

    <div class="ad-by-stages">
        <div v-for="(item, index) in timeList"
             :key="item.adTime"
             class="time-item"
        >
            <div :class="currentTime === index ? 'ad-time-piker active' : 'ad-time-piker'">
                <el-date-picker v-model="item.activeTime"
                                type="datetimerange"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期"
                                format="YYYY-MM-DD HH:mm:ss"
                                value-format="YYYY-MM-DD HH:mm:ss"
                                @change="(val) => changeTime(val, item, index)"
                />

                <span :class="currentTime === index ? 'sort active' : 'sort'"
                      @click="selectTime(index, item)"
                >
                    {{ index + 1 }}
                </span>
            </div>

            <div class="icon-btns">
                <el-icon v-if="index === timeList.length - 1"
                         class="add"
                         @click.stop="addAdTime(item, index)"
                >
                    <CirclePlus />
                </el-icon>

                <el-icon v-if="timeList.length > 1"
                         class="del"
                         @click.stop="delTime(item, index)"
                >
                    <Delete />
                </el-icon>
            </div>
        </div>
    </div>

    <SearchTable v-bind="gridOptions"
                 :loading="isLoading"
                 :data="records"
                 :height="tableHeight"
    >
        <template #plate="row">
            {{ useDict('PlateType', row.row.plate) }}
        </template>

        <template #activeStatus="{ row }">
            <el-switch v-model="row.activeStatus"
                       :active-value="1"
                       :inactive-value="0"
                       @change="switchActiveStatus(row)"
            />
        </template>

        <template #operate="{ row }">
            <el-button class="small"
                       type="primary"
                       text
                       @click="goToEdit(row)"
            >
                编辑
            </el-button>

            <el-button class="small"
                       text
                       type="warning"
                       @click="deleteConfirm(row)"
            >
                删除
            </el-button>
        </template>
    </SearchTable>

    <div class="total">
        共{{ total }}项数据
    </div>

    <addOrEditGoods ref="addOrEditRef"
                    v-model:visible="visible"
                    v-model:id="editId"
                    v-model:currentSnapshotId="currentSnapshotId"
                    @refresh="getGoodsList"
    />
</template>

<style lang="scss" scoped>
:deep(.small.el-button) {
    padding: 4px;
    margin-left: 6px;
}

.total {
    height: 50px;
    line-height: 50px;
    color: #4e5969;
}

:deep(.vxe-toolbar) {
    display: none;
}

.ad-by-stages {
    display: flex;
    flex-wrap: wrap;

    .time-item {
        display: flex;
        width: 310px;
        margin-bottom: 12px;

        :deep(.ad-time-piker) {
            display: flex;
            align-items: center;
            position: relative;

            > .sort {
                position: absolute;
                left: 0;
                top: 0;
                width: 30px;
                height: 32px;
                display: block;
                font-size: 16px;
                line-height: 32px;
                border-right: 1px solid #e6ebf5;
                text-align: center;
                cursor: pointer;

                &.active {
                    color: var(--el-color-primary);
                    border-right: 1px solid var(--el-color-primary);
                }
            }

            &.active {
                .el-range-editor.el-input__wrapper {
                    border: 1px solid var(--el-color-primary);
                }
            }
        }

        :deep(.el-range-editor.el-input__wrapper) {
            width: 260px;
            padding-left: 40px;
        }

        .icon-btns {
            display: flex;
            align-items: center;
            margin-left: 10px;

            .el-icon {
                font-size: 18px;
                cursor: pointer;

                &.add {
                    color: var(--el-color-primary);
                    margin-right: 6px;
                }
            }
        }
    }
}

.top {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    .group-title {
        margin-left: 20px;
        font-size: 16px;
        font-weight: bold;
        cursor: pointer;
    }
}
</style>
